#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: shijianbo
@Email:
@Time: 2023/4/11 14:35
@File: mssql.py
"""
import threading
import pymssql
from .basic import DatabaseUtil

# jdbc不是很好处理...版本问题
class MssqlUtil(DatabaseUtil):

    def __init__(self,user,password,ip,port=1433,**kwargs):
        self.DB = {}
        self.CURSOR = {}
        if 'server' in kwargs:
            server=kwargs['server']
        else:
            server='master'
        self.dbkeywords={
            'user':user,
            'password':password,
            'server':ip,
            'port':str(port),
            'database':server,
        }

    def __exit__(self, exc_type, exc_val, exc_tb):
        for cursor in self.CURSOR.values():
            cursor.close()
        for db in self.DB.values():
            db.close()

    def commit(self):
        for db in self.DB.values():
            db.commit()

    def rollback(self):
        for db in self.DB.values():
            db.rollback()

    @property
    def db(self):
        _id=threading.get_ident()
        if _id not in self.DB:
            self.DB[_id]=pymssql.connect(**self.dbkeywords)
        return self.DB[_id]

# class MssqlUtil(DatabaseUtil):
#
#     def __init__(self,user,password,ip,port=1433,**kwargs):
#         self.CURSOR = {}
#         if 'server' in kwargs:
#             server=kwargs['server']
#         else:
#             server='master'
#         jclassname = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
#         url=f"jdbc:sqlserver://{ip}:{port};databaseName={server}"
#         driver_args=[user,password]
#         jarFile=self.getJarFile(__file__,'mssql-jdbc-9.2.0.jre8.jar')
#         self.db=jaydebeapi.connect(jclassname,url,driver_args,jarFile)
#         self.db.jconn.setAutoCommit(False)

if __name__ == '__main__':
    with MssqlUtil('sa','tzfxCS@1','192.168.70.69',server='WIND') as db:
        print(db.execsql(f"select * from jydb.dbo.Bond_ConBDFluctuation"))